# ommbot/persist.py
#
#

""" allow data to be pickled to disk .. creating the persisted object
    restores the data
"""

__copyright__ = 'this file is in the public domain'

from ommbot.world import rlog
import pickle
import thread
import os

class Persist(object):

    """ persist data attribute to pickle file """

    def __init__(self, filename):
        self.fn = filename
        self.lock = thread.allocate_lock()
        try:
            datafile = open(filename, 'r')
        except IOError:
            self.data = None
            return
        self.data = pickle.load(datafile)
        datafile.close()
        rlog(0, 'persist', 'loaded %s' % filename)

    def save(self):
        """ save persist data """
        try:
            self.lock.acquire()
            # first save to temp file and when done rename
            tmp = self.fn + '.tmp'
            datafile = open(tmp, 'w')
            pickle.dump(self.data, datafile)
            datafile.close()
            os.rename(tmp, self.fn)
            rlog(0, 'persist', 'saved %s' % self.fn)
        finally:
            self.lock.release()
